package com.ayu.shortlink.engine.mq.listener;


import com.alibaba.fastjson2.JSON;
import com.ayu.shortlink.engine.dao.mapper.CouponTemplateMapper;
import com.ayu.shortlink.engine.mq.basics.base.MessageWrapper;
import com.ayu.shortlink.engine.mq.basics.event.DeductCouponTransactionEvent;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.Message;

import java.util.concurrent.TimeUnit;

/**
 * 扣减优惠券本地监听事务
 */
@Slf4j
@RocketMQTransactionListener(rocketMQTemplateBeanName = "rocketMQTemplate")
public class DeductCouponTransactionListener implements RocketMQLocalTransactionListener {
    @Autowired
    private CouponTemplateMapper couponTemplateMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private final static String TRANSACTION_SUCCESS_KEY = "transaction_success_key:%s";

    /**
     * 执行本地事务
     * @param message
     * @param o
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        // 获取消息体
        MessageWrapper messageWrapper = JSON.parseObject((String) message.getPayload(), MessageWrapper.class);
        DeductCouponTransactionEvent event = (DeductCouponTransactionEvent)messageWrapper.getMessage();

        try {
            Long res = couponTemplateMapper.deductCouponTemplateStock(event.getStock(), event.getShopNumber(), event.getCouponTemplateId());
            if (SqlHelper.retBool(res)){
                //同时设置Redis表示已经完成 后续去查Redis即可知道是否执行成功
                String key = String.format(TRANSACTION_SUCCESS_KEY, event.getCouponTemplateId());
                stringRedisTemplate.opsForValue().set(key,"OK",15, TimeUnit.MINUTES);
                return RocketMQLocalTransactionState.COMMIT;
            }
        }catch (Exception e){
            log.error("执行本地事务出现异常:{}", e.toString());
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }

    /**
     * 回查事务
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        // 获取消息体
        MessageWrapper messageWrapper = JSON.parseObject((String) message.getPayload(), MessageWrapper.class);
        DeductCouponTransactionEvent event = (DeductCouponTransactionEvent)messageWrapper.getMessage();
        String key = String.format(TRANSACTION_SUCCESS_KEY, event.getCouponTemplateId());

        if(stringRedisTemplate.hasKey(key).equals(Boolean.TRUE)){
            return RocketMQLocalTransactionState.COMMIT;
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
